<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户端ID" prop="sbClientid">
        <el-input
          v-model="queryParams.sbClientid"
          placeholder="请输入客户端ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
	  
	  <el-form-item label="所属机构" prop="sbXxid" label-width="68px">
<!-- 	    <el-input
	      v-model="queryParams.deptName"
	      placeholder="请输入所属机构"
	      clearable
	      @keyup.enter="handleQuery"
	    /> -->
		
		  <el-select v-model="queryParams.sbXxid" placeholder="所属机构" style="width: 200px;" :disabled="!checkRole(['admin','common'])">
			<el-option
			  v-for="d in deptlist"
			  :key="d.dept_id"
			  :label="d.dept_name"
			  :value="d.dept_id"
			></el-option>
		  </el-select>
      </el-form-item>
	  
	  <el-form-item label="所属人员" prop="sbXxid2">
	    <el-input
	      v-model="queryParams.sbXxid2"
	      placeholder="请输入所属人员"
	      clearable
	      @keyup.enter="handleQuery"
	    />
	  </el-form-item>
	  
	  
	  
    <!--  
	
	<el-form-item label="登录用户" prop="sbLoginuser">
	  <el-input
	    v-model="queryParams.sbLoginuser"
	    placeholder="请输入登录用户"
	    clearable
	    @keyup.enter="handleQuery"
	  />
	</el-form-item>
	<el-form-item label="设备名称" prop="sbName">
	  <el-input
	    v-model="queryParams.sbName"
	    placeholder="请输入设备名称"
	    clearable
	    @keyup.enter="handleQuery"
	  />
	</el-form-item>
	
	
	<el-form-item label="订阅主题" prop="sbTopic">
        <el-input
          v-model="queryParams.sbTopic"
          placeholder="请输入订阅主题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否在线 1在线 0不在线" prop="sbIszx">
        <el-input
          v-model="queryParams.sbIszx"
          placeholder="请输入是否在线 1在线 0不在线"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用 1启用 0停用" prop="sbIsqy">
        <el-input
          v-model="queryParams.sbIsqy"
          placeholder="请输入是否启用 1启用 0停用"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否删除 1正常 0删除" prop="sbIsdel">
        <el-input
          v-model="queryParams.sbIsdel"
          placeholder="请输入是否删除 1正常 0删除"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="连接节点" prop="sbJiedian">
        <el-input
          v-model="queryParams.sbJiedian"
          placeholder="请输入连接节点"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="sbCreatetime">
        <el-date-picker clearable
          v-model="queryParams.sbCreatetime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="IP地址" prop="sbIp">
        <el-input
          v-model="queryParams.sbIp"
          placeholder="请输入IP地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新时间" prop="sbUpdatetime">
        <el-date-picker clearable
          v-model="queryParams.sbUpdatetime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
		<el-col :span="4" v-if="checkRole(['admin','common'])">
		  <el-select v-model="tbdept" placeholder="请选择同步的机构">
		    <el-option
		      v-for="d in deptlist"
		      :key="d.dept_id"
		      :label="d.dept_name"
		      :value="d.dept_id"
		    ></el-option>
		  </el-select>
		</el-col>
		
		<el-col :span="1.5">
		  <el-button
		    type="primary"
		    plain
		    icon="RefreshRight"
		    @click="handleTB" 
		  >同步设备列表</el-button>
		</el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['erysys:shebei:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['erysys:shebei:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['erysys:shebei:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['erysys:shebei:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :show-overflow-tooltip="true" v-loading="loading" :data="shebeiList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="设备ID" align="center" prop="id"/>
      <el-table-column label="客户端ID" align="center" prop="sbClientid" min-width="200"/>
      <el-table-column label="登录用户" align="center" prop="sbLoginuser" />
      <el-table-column label="订阅主题" align="center" prop="sbTopic" />
      <!-- <el-table-column label="项目分类" align="center" prop="sbTctype" /> -->
      <!-- <el-table-column label="协议类型" align="center" prop="sbXytype" /> -->
      <!-- <el-table-column label="数据类型" align="center" prop="sbTcdatatype" /> -->
      <!-- <el-table-column label="是否删除" align="center" prop="sbIsdel" /> -->
	  <el-table-column label="是否在线" align="center" prop="sbIszx">
	    <template #default="scope">
	      <dict-tag :options="ery_zxzt" :value="scope.row.sbIszx"/>
	    </template>
	  </el-table-column>
	  <el-table-column label="删除状态" align="center" prop="sbIsdel">
	    <template #default="scope">
	      {{scope.row.sbIsdel=='1'?'正常':'删除'}}
	    </template>
	  </el-table-column>
	  <el-table-column label="是否启用" align="center" prop="sbIsqy">
	    <template #default="scope">
	      <!-- <dict-tag :options="tc_qyzt" :value="scope.row.sbIsqy"/> -->
	      {{scope.row.sbIsqy=='1'?'启用':'停用'}}
	    </template>
	  </el-table-column>
      <el-table-column label="连接节点" align="center" prop="sbJiedian" />
      <!-- <el-table-column label="所属部门ID" align="center" prop="sbXxid" /> -->
      <el-table-column label="所属机构" align="center" prop="deptName" min-width="200"/>
      <el-table-column label="所属用户ID" align="center" prop="sbXxid2" />
      <el-table-column label="设备名称" align="center" prop="sbName" />
      <el-table-column label="IP地址" align="center" prop="sbIp" />
      <el-table-column label="无线" align="center" prop="sbWifi" />
      <el-table-column label="蓝牙" align="center" prop="sbBlue" />
      <el-table-column label="运动设置" align="center" prop="sbSportset" />
	  <el-table-column label="创建时间" align="center" prop="sbCreatetime" width="140">
	    <template #default="scope">
	      <span>{{ parseTime(scope.row.sbCreatetime, '{y}-{m}-{d} {h}:{i}') }}</span>
	    </template>
	  </el-table-column>
	  <el-table-column label="更新时间" align="center" prop="sbUpdatetime" width="160">
	    <template #default="scope">
	      <span>{{ parseTime(scope.row.sbUpdatetime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
	    </template>
	  </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  fixed="right"  min-width="120">
        <template #default="scope">
		  <el-button link type="primary" icon="RefreshLeft" @click="handleUpdateState(scope.row)">更新状态</el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['erysys:shebei:edit']">修改</el-button> -->
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['erysys:shebei:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="shebeiRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户端ID" prop="sbClientid">
          <el-input v-model="form.sbClientid" placeholder="请输入客户端ID" />
        </el-form-item>
        <el-form-item label="登录用户" prop="sbLoginuser">
          <el-input v-model="form.sbLoginuser" placeholder="请输入登录用户" />
        </el-form-item>
        <el-form-item label="订阅主题" prop="sbTopic">
          <el-input v-model="form.sbTopic" placeholder="请输入订阅主题" />
        </el-form-item>
        <el-form-item label="是否在线 1在线 0不在线" prop="sbIszx">
          <el-input v-model="form.sbIszx" placeholder="请输入是否在线 1在线 0不在线" />
        </el-form-item>
        <el-form-item label="是否启用 1启用 0停用" prop="sbIsqy">
          <el-input v-model="form.sbIsqy" placeholder="请输入是否启用 1启用 0停用" />
        </el-form-item>
        <el-form-item label="是否删除 1正常 0删除" prop="sbIsdel">
          <el-input v-model="form.sbIsdel" placeholder="请输入是否删除 1正常 0删除" />
        </el-form-item>
        <el-form-item label="连接节点" prop="sbJiedian">
          <el-input v-model="form.sbJiedian" placeholder="请输入连接节点" />
        </el-form-item>
        <el-form-item label="创建时间" prop="sbCreatetime">
          <el-date-picker clearable
            v-model="form.sbCreatetime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属部门ID" prop="sbXxid">
          <el-input v-model="form.sbXxid" placeholder="请输入所属部门ID" />
        </el-form-item>
        <el-form-item label="设备名称" prop="sbName">
          <el-input v-model="form.sbName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="IP地址" prop="sbIp">
          <el-input v-model="form.sbIp" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="更新时间" prop="sbUpdatetime">
          <el-date-picker clearable
            v-model="form.sbUpdatetime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Shebei">
import { checkPermi, checkRole } from "@/utils/permission"; // 1. 导入权限判断函数
import { listShebei, getShebei, delShebei, addShebei, updateShebei,sbtongbu,updateShebeiState,getDeptList } from "@/api/erysys/shebei";
import useUserStore from '@/store/modules/user'
import { onMounted } from "vue";
var userStore=useUserStore();
// console.log(userStore.deptid)

const { proxy } = getCurrentInstance();
const { ery_zxzt } = proxy.useDict('ery_zxzt');
const shebeiList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const tbdept = ref("");
const deptlist = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sbClientid: null,
    sbLoginuser: null,
    sbTopic: null,
    sbTctype: null,
    sbIszx: null,
    sbIsqy: null,
    sbXytype: null,
    sbTcdatatype: null,
    sbIsdel: null,
    sbJiedian: null,
    sbCreatetime: null,
    sbXxid: null,
    sbName: null,
    sbIp: null,
    sbUpdatetime: null,
    sbXxid2: null,
    sbWifi: null,
    sbBlue: null,
    sbSportset: null,
	deptName:null,
  },
  rules: {
    sbClientid: [
      { required: true, message: "客户端ID不能为空", trigger: "blur" }
    ],
    sbLoginuser: [
      { required: true, message: "登录用户不能为空", trigger: "blur" }
    ],
    sbXxid: [
      { required: true, message: "所属部门ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


/** 查询设备列表 */
function getList() {
  loading.value = true;
  listShebei(queryParams.value).then(response => {
    shebeiList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    sbClientid: null,
    sbLoginuser: null,
    sbTopic: null,
    sbTctype: null,
    sbIszx: null,
    sbIsqy: null,
    sbXytype: null,
    sbTcdatatype: null,
    sbIsdel: null,
    sbJiedian: null,
    sbCreatetime: null,
    sbXxid: null,
    sbName: null,
    sbIp: null,
    sbUpdatetime: null
  };
  proxy.resetForm("shebeiRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getShebei(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["shebeiRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateShebei(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addShebei(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备编号为"' + _ids + '"的数据项？').then(function() {
    return delShebei(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('erysys/shebei/export', {
    ...queryParams.value
  }, `shebei_${new Date().getTime()}.xlsx`)
}


/* 同步设备  */
function handleTB() {
	// let deptid=userStore.deptid;
	let deptid=tbdept.value;
	if(deptid==null || deptid==""){
		proxy.$modal.msgError("获取参数错误");
	}else{
		loading.value = true;
		sbtongbu({"deptid":deptid}).then(response => {
		  // console.log(response)
		  proxy.$modal.msgSuccess(response.msg);
		  loading.value = false;
			handleQuery();
		}).catch(error => {
			// console.log('I catch:', error);
			loading.value = false;
		})
		// proxy.$modal.msgSuccess("暂未开发");
	}
}
/** 同步状态按钮操作 */
function handleUpdateState(row) {
	// console.log(row)
	// console.log(list)
	// let data={"clientid":row.sbClientid};
    open.value = false;
	updateShebeiState(row).then(response => {
		// console.log(response)
		proxy.$modal.msgSuccess("同步成功");
		for (let i = 0; i < shebeiList.value.length; i++) {
		    if(response.data.id==shebeiList.value[i].id){
				shebeiList.value[i]=response.data;
				return;
			}
		}
		
		open.value = false;
	});
}

 onMounted(() => {
      // console.log('组件已经挂载')
	getList();
	
	if(checkRole(['admin','common'])){
		getDeptList({"deptid":tbdept}).then(response => {
		  deptlist.value=response.data;
		});
	}
	tbdept.value=userStore.deptid;
	queryParams.value.sbXxid=userStore.deptid;
	console.log(queryParams.value)
 })
</script>
